import {createAsyncThunk, createSlice} from '@reduxjs/toolkit'
import { getDoctorList } from '../api/api'
// 异步请求医生列表分页数据：
export const getDoctorsAsync = createAsyncThunk('receiveDoctorListAsync',
(paylaod)=>{
  // 返回actions函数的结果给state.
 return getDoctorList(paylaod).then(res=>{
    if(res.code === 0){
      // 返回到getDoctorList（）调用点
      return res.data;
    }
  })
})

export const doctorSlice = createSlice({
  name: 'doctors',
  initialState: {
    loading: false,
    list: [
      { did: 1, dname: '张三' },
      { did: 2, dname: '李四' },
      { did: 3, dname: '王二' },
      { did: 4, dname: '赵四' }
    ]
  },
  reducers: {
    receiveDoctorList: (state, actions)=>{
      state.list = actions.payload
    },
    addList:(state,actions)=>{
      // state.list.push(actions.payload)  // ?能不能实现响应式？？？？
      let arr = JSON.parse(JSON.stringify(state))
      arr.push(actions.payload)
      state = arr;
    }
  },
// 异步actions的监听器的配置；
  extraReducers: {
    // 异步actions的成功状态时执行的逻辑：
    // 监听对应的异步action的执行结果，三种状态和Promise一样。fulfilled时，我们去修改state中的List对象的值。这样就实现更新了。
    [getDoctorsAsync.fulfilled](state, actions){
      state.list = actions.payload
      state.loading = false
    },
    // 失败的状态
    [getDoctorsAsync.rejected](state, {payload}){
      alert('请求后端接口失败')
      state.loading = false
    },
    // 刚开始发送异步请求时：
    [getDoctorsAsync.pending](state, {payload}){
      state.loading = true
      console.log('显示loding。。。。。');
      // 如loading ，加载效果。开始显示loading, 失败和成功时不显示Loading效果。
    },
    // [testAsync.fulfilled](){}
  }
})

// 简单的引用类型： {a:1,b:2}, [1,2,34],只需要进行浅克隆
// 复杂的引用类型：{a:[],b:{c:10}}, [{did:1,dname:''},{},{}], 这种必须进行深克隆。

export const {receiveDoctorList,addList } = doctorSlice.actions;

export default doctorSlice.reducer;